<template>
  <div v-loading="loading">
    <div class="text-right" v-if="isView">
      <el-button @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button @click="handleExport" :loading="downloadLoading">
        <i class="fa fa-fw fa-download"></i>
        导出
      </el-button>
    </div>
    <div :id="printId">
      <table class="w-100">
        <tr>
          <td colspan="7" class="text-center">
            <h4>{{ orgName }}</h4>
            <h5>风险审查报告</h5>
          </td>
        </tr>
      </table>
      <table class="mt-5 table table-bordered table-sm bg-white table-vertical-middle">
        <colgroup>
          <col width="11%" />
          <col width="11%" />
          <col width="19%" />
          <col width="12%" />
          <col width="18%" />
          <col width="11%" />
          <col width="18%" />
        </colgroup>
        <tr>
          <td rowspan="4" class="text-center">项目概况</td>
          <td class="text-center">客户名称</td>
          <td>{{ relatedData.customer_name }}</td>
          <td class="text-center">申保金额(万元)</td>
          <td>{{ relatedData.approved_funds }}</td>
          <td class="text-center">期限(月)</td>
          <td>{{ relatedData.months }}</td>
        </tr>
        <tr>
          <td class="text-center">项目地址</td>
          <td>{{ relatedData.address }}</td>
          <td class="text-center">联系人</td>
          <td>{{ relatedData.corp_name }}</td>
          <td class="text-center">联系电话</td>
          <td>{{ relatedData.mobile_no }}</td>
        </tr>
        <tr>
          <td class="text-center">合作银行</td>
          <td>{{ relatedData.bank_name }}</td>
          <td class="text-center">贷款种类</td>
          <td :class="tdClass">
            <span v-if="isView">{{ debitType[riskData.load_class] }}</span>
            <c-select
              v-else
              v-model="riskData.load_class"
              :options="debitType"
              placeholder="贷款种类"
            ></c-select>
          </td>
          <td class="text-center">担保费(元)</td>
          <td>{{ relatedData.gua_fee }}</td>
        </tr>
        <tr>
          <td class="text-center">风险经理</td>
          <td>{{ relatedData.res_person_risk_point }}</td>
          <td class="text-center">受理日期</td>
          <td>{{ $utils.dateFormat(relatedData.item_date, 'yyyy-MM-dd') }}</td>
          <td class="text-center">保证金(元)</td>
          <td>{{ relatedData.bond }}</td>
        </tr>
        <tr>
          <td colspan="7" class="text-center"><b>评 审 内 容</b></td>
        </tr>
        <tr>
          <td colspan="2">被担保主体主体资格审核</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.qual_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保主体主体资格审核"
              v-model="riskData.qual_approval"
            ></el-input>
          </td>
        </tr>

        <tr>
          <td colspan="2">被担保主体资料完整性审核</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.material_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保主体资料完整性审核"
              v-model="riskData.material_approval"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">被担保企业经营状况审查</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.bus_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保企业经营状况审查"
              v-model="riskData.bus_approval"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">被担保企业资产状况审查</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.assert_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保企业资产状况审查"
              v-model="riskData.assert_approval"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">被担保企业财务状况评审</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.final_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保企业财务状况评审"
              v-model="riskData.final_approval"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">被担保客户借款用途及还款来源审查</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.repay_approval }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="被担保客户借款用途及还款来源审查"
              v-model="riskData.repay_approval"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td rowspan="5">被担保企业项目风险分析</td>
          <td>1.信用风险</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.risk_analysis_credit }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="信用风险"
              v-model="riskData.risk_analysis_credit"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>2.财务风险</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.risk_analysis_final }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="财务风险"
              v-model="riskData.risk_analysis_final"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>3.关联法律风险</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.risk_analysis_law }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="关联法律风险"
              v-model="riskData.risk_analysis_law"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>4.市场风险</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.risk_analysis_market }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="市场风险"
              v-model="riskData.risk_analysis_market"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>5.抵质押物风险</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.risk_analysis_pledge }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="抵质押物风险"
              v-model="riskData.risk_analysis_pledge"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">反担保措施审查</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.review_gua_method }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="反担保措施审查"
              v-model="riskData.review_gua_method"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">风险控制措施及建议</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.review_risk_control }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="风险控制措施及建议"
              v-model="riskData.review_risk_control"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2">需补充调查内容</td>
          <td colspan="5" :class="tdClass">
            <span v-if="isView">{{ riskData.review_material }}</span>
            <el-input
              v-else
              type="textarea"
              :autosize="{ minRows: 3 }"
              placeholder="需补充调查内容"
              v-model="riskData.review_material"
            ></el-input>
          </td>
        </tr>
        <template v-for="(p, index) of option">
          <tr :key="`${index}-1`">
            <td colspan="2" rowspan="2">{{ p.label }}</td>
            <td colspan="5" :class="p.editable ? tdClass : ''">
              <span v-if="!p.editable || isView">{{ p.approval_option || '-' }}</span>
              <el-input
                v-else
                type="textarea"
                v-model="p.approval_option"
                :autosize="{ minRows: 3 }"
                placeholder="评审意见"
              ></el-input>
            </td>
          </tr>
          <tr :key="`${index}-2`">
            <td colspan="3" class="p-2">
              签名：
              <span v-if="p.editable || p.status > 0">{{ p.sign }}</span>
            </td>
            <td colspan="2" class="p-2">
              <span v-if="p.editable || p.status > 0">{{ p.approval_time || reportDate }}</span>
            </td>
          </tr>
        </template>
      </table>
    </div>
    <div class="text-center mt-3" v-if="!isView">
      <el-button @click="handleSubmit" type="primary" :loading="submitLoading" class="btn-long">
        保存
      </el-button>
      <el-button @click="beforeClose" :loading="submitLoading" class="btn-long">取消</el-button>
    </div>
  </div>
</template>

<script>
import { printWithIframe, excelTableExport, domHasClass } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
export default {
  props: {
    queryId: String,
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      debitType: {
        1: '流贷',
        2: '固贷',
        3: '其他',
      },
      loading: false,
      relatedData: {},
      submitLoading: false,
      riskData: {
        id: '',
        qual_approval: '',
        material_approval: '',
        bus_approval: '',
        assert_approval: '',
        final_approval: '',
        repay_approval: '',
        risk_analysis_credit: '',
        risk_analysis_final: '',
        risk_analysis_law: '',
        risk_analysis_market: '',
        risk_analysis_pledge: '',
        review_gua_method: '',
        review_risk_control: '',
        review_material: '',
        load_class: '',
      },
      downloadLoading: false,
      option: [],
    }
  },

  created() {},
  computed: {
    ...mapGetters(['org', 'user']),
    userId() {
      return this.user.userId
    },
    realName() {
      return this.user.realName
    },
    isRiskManage() {
      return this.user.job === 'org_r_manage'
    },
    orgName() {
      return this.org.orgName
    },
    isView() {
      return !this.option.some(item => item.editable)
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    reportDate() {
      return this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
    },
    printId() {
      return `${this.queryId}-risk-report`
    },
    tableTitle() {
      return `风险审查报告-${this.relatedData.customer_name}`
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  methods: {
    getEditable(user, approve) {
      let optionData = []
      const wfnKey = ['RISK_REVIEW_APPROVAL-RES', 'RISK_REVIEW_APPROVAL-RES_MANAGE']
      wfnKey.forEach(key => {
        const data = approve.find(item => item.wfn_key === key) || {}
        const record = data.workflow_record?.[0] ?? {}
        const option = {
          label: data.wfn_name || record.approval_person,
          sign: record.approval_person,
          status: +(record.approval_status || ''),
          task_id: record.task_id,
          wf_approval_user_id: record.wf_approval_user_id,
          approval_option: record.approval_option,
          approval_time: this.$utils.dateFormat(record.approval_time, 'yyyy-MM-dd'),
          wfn_key: data.wfn_key,
          workflow_key: data.workflow_key,
          id: record.id,
        }
        optionData.push(option)
      })
      optionData = optionData.map((item, index) => {
        const lastStatus = index === 0 ? 1 : optionData[index - 1].status
        const nextStatus =
          index + 1 < optionData.length ? optionData[index + 1].status : item.status
        item.editable =
          user.userId === item.wf_approval_user_id &&
          lastStatus === 1 &&
          nextStatus === 0 &&
          !!item.task_id
        return item
      })
      // 风控主管可修改风控员意见
      optionData[0].editable = optionData[0].editable || optionData[1].editable
      return optionData
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      const params = { 'customer_related_id.eq': this.queryId }
      const serviceName = this.$serviceName
      Promise.all([
        this.$api.getData(serviceName, 'customer_related', params),
        this.$api.getData(serviceName, 'risk_review', params),
      ])
        .then(([related, risk]) => {
          this.relatedData = related?.data?.[0] || {}
          const data = risk?.data?.[0] || {}
          Object.keys(this.riskData).forEach(key => {
            this.riskData[key] = data[key] || ''
          })
          this.$http
            .get(`/api/credit/wf/?wfKey=RISK_REVIEW_APPROVAL&wfRelatedId=${this.queryId}`)
            .then(res => {
              const data = res?.data ?? []
              this.option = this.getEditable(this.user, data)
            })
        })
        .catch(() => {
          this.relatedData = {}
          this.riskData = {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      const { id, ...data } = { ...this.riskData }
      data.customer_related_id = this.queryId
      const promiseAll = []
      const submitData = []

      for (let i = 0; i < this.option.length; i++) {
        const item = this.option[i]
        if (item.editable) {
          if (!item.approval_option) {
            return this.$message.warning('请输入审查意见')
          }
          const row = {
            approval_option: item.approval_option,
            id: item.id,
            approval_time: item.approval_time,
            approval_person: item.approval_person,
            approval_status: item.status,
            task_id: item.task_id,
            wf_related_id: item.wf_related_id,
            wfn_key: item.wfn_key,
            workflow_key: item.workflow_key,
          }
          if (row.approval_status === 0) {
            row.approval_time = this.$utils.dateFormat(new Date())
            row.approval_person = this.user.realName
            row.approval_status = 1
            row.task_id = item.task_id
            row.wf_related_id = this.queryId
            row.wfn_key = item.wfn_key
            row.workflow_key = item.workflow_key
          }
          submitData.push(row)
        }
      }

      submitData.forEach(item => {
        if (!item.id) {
          promiseAll.push(this.$api.addData('credit', 'workflow_record', item))
        } else {
          promiseAll.push(this.$api.updateData('credit', 'workflow_record', item.id, item))
        }
      })

      if (!id) {
        promiseAll.push(this.$api.addData(this.$serviceName, 'risk_review', data))
      } else {
        promiseAll.push(this.$api.updateData(this.$serviceName, 'risk_review', id, data))
      }

      Promise.all(promiseAll).then(() => {
        this.$message.success('保存成功！')
        this.getData()
        this.beforeClose()
        this.$emit('success', true)
      })
    },
    beforeClose() {
      this.$emit('close', false)
    },
    printPage() {
      printWithIframe(document.getElementById(this.printId))
    },
    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      this.downloadLoading = true
      excelTableExport(this.printId, this.tableTitle, {
        styles: {
          border: borderAllThin,
          alignment: {
            vertical: 'center',
            horizontal: 'left',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 16,
              name: '方正小标宋简体',
            },
          },
          A6: {
            font: {
              sz: 14,
            },
          },
        },
        cols: [
          { wch: 15 },
          { wch: 16 },
          { wch: 18 },
          { wch: 16 },
          { wch: 18 },
          { wch: 16 },
          { wch: 18 },
        ],
        rows: {
          0: { hpx: 48 },
          ...this.getRowHeight(),
        },
        cellHandler({ value, td }) {
          const style = {}
          if (domHasClass(td, 'text-center')) {
            style.alignment = { horizontal: 'center' }
          }
          return { value, style }
        },
      }).finally(() => {
        this.downloadLoading = false
      })
    },
    getRowHeight() {
      const row = {}
      for (let i = 6; i < 23; i++) {
        if (i !== 21) {
          row[i] = { hpx: 35 }
        }
      }
      return row
    },
  },
}
</script>
<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
</style>
